<template>
  <view class="container">
    <view class="exam-title">{{ paperInfo.title }}</view>
    <view class="hor-layout-center exam-time" v-if="paperInfo.sel_time">
      <view>开始时间：</view>
      <uni-dateformat :date="paperInfo.sel_time[0]" format="yyyy/MM/dd hh:mm"></uni-dateformat>
    </view>
    <view class="hor-layout-center exam-time" style="margin-top: 5px;" v-if="paperInfo.sel_time">
      <view>结束时间：</view>
      <uni-dateformat :date="paperInfo.sel_time[1]" format="yyyy/MM/dd hh:mm"></uni-dateformat>
    </view>
    <view class="hor-layout-side exam-time" style="margin-top: 5px;">
      <view>答题时间：10分钟</view>
      <view>剩余时间：
        <text style="color: red">{{ getLeaveTime }}</text>
      </view>
    </view>
    <!-- 题目列表 -->
    <view v-for="(item,index) in question_list" :key="index" class="question-item">
      <view v-if="unComplete==index" style="text-align: center;color:#f63d46;">未作答</view>
      <!-- 题目 -->
      <view class="question-title">
        <text style="font-weight: bold;">{{ index + 1 }}.</text>
        <text v-if="item.type===0&&item.single">【单选】</text>
        <text v-if="item.type===0&&!item.single">【多选】</text>
        <text>{{ item.title }}</text>
        <text class="question-score">({{ item.score }}分)</text>
      </view>
      <!-- 选择题 -->
      <view style="margin: 10px;" v-if="item.type==0">
        <view v-for="(opt,ind) in item.options" :key="ind">
          <view>{{ opt.text }}. {{ opt.content }}</view>
        </view>
        <view class="hor-layout-center" style="margin-top: 10px;">
          <view>选择：</view>
          <uni-data-checkbox :multiple="item.type===0&&!item.single" v-model="item.uAnswer"
                             :localdata="item.options" @change="unComplete=-1"></uni-data-checkbox>
        </view>
      </view>
      <!-- 判断题 -->
      <view class="hor-layout-center" style="margin: 10px;" v-if="item.type==1">
        <view>选择答案：</view>
        <radio-group @change="selectAnswer(item,$event.detail.value)">
          <label>
            <radio style="transform:scale(0.7)" value="true" :checked="item.uDecide==='true'"/>
            正确
          </label>
          <label style="margin-left: 20px;">
            <radio style="transform:scale(0.7)" value="false" :checked="item.uDecide==='false'"/>
            错误
          </label>
        </radio-group>
      </view>
    </view>
    <view class="ver-layout-center-all submit-view" @click="submitExam">
      <uni-icons type="upload" size="20" color="white"></uni-icons>
      <text style="font-size: small">提交</text>
    </view>

  </view>
</template>

<script>
import {getMinuteValue, convertDateTime} from "@/common/common.js"
import UniDataChecklist from "../../components/uni-data-checkbox/uni-data-checkbox";
import {examDetail, home, rank} from "../../router"

export default {
  components: {UniDataChecklist},
  data() {
    return {
      paperInfo: {},
      question_list: [],
      unComplete: -1,
      startTime: '',
      leaveTime: 5 * 60,
      timer: ''
    }
  },
  computed: {
    getLeaveTime() {
      if (this.leaveTime < 60) {
        return `${this.leaveTime}秒`
      } else {
        let minute = Math.floor(this.leaveTime / 60)
        let second = this.leaveTime % 60
        return `${minute}分${second}秒`
      }
    }
  },
  onLoad(event) {
    this.startTime = new Date().getTime()
    let paperId = event.paperId
    this.paperId = paperId
    this.getPaperInfo()
    this.startCountdown()
  },
  onUnload() {
    if (this.timer) clearInterval(this.timer)
  },
  methods: {
    startCountdown() {
      let timer = setInterval(() => {
        console.log("timer")
        this.leaveTime = this.leaveTime - 1
        if (this.leaveTime <= 0 && timer) {
          uni.showToast({title: "答题时间到！"});
          clearInterval(timer)
          this.submitExamRequest()
        }
      }, 1000)
      this.timer = timer
    },
    isAnswerChecked(answer, opt) {
      // item.uAnswer===opt.text
      // console.log("isAnswerChecked-------", answer, opt)
      return answer && answer.indexOf(opt) > -1
    },
    selectAnswer(item, value) {
      // console.log("selectDecide", item, value)
      this.unComplete = -1;
      let question_list = this.question_list
      question_list.forEach(que => {
        if (que._id === item._id && item.type === 0) item.uAnswer = value
        if (que._id === item._id && item.type === 1) item.uDecide = value
      })
      this.question_list = question_list
    },
    getPaperInfo() {
      this.$request('exam/exam/getPaperInfo', {
        paperId: this.paperId
      }).then(res => {
        // debugger
        let result = res.data
        if (result) {
          result.question_list.forEach(que => {
            if (que.options) que.options.forEach(opt => opt.value = opt.text)
          })
          this.paperInfo = result
          this.question_list = result.question_list
        } else
          uni.showToast({title: '暂无数据'})
      }).catch(err => {
        // debugger
        uni.showToast({title: err.message || "请求失败!"})
      })
    },
    submitExam() {
      console.log(this.question_list)
      let unComplete = -1;
      for (let index = 0; index < this.question_list.length; index++) {
        let item = this.question_list[index]
        if (item.type == 0 && (!item.uAnswer || item.uAnswer.length <= 0)) {
          unComplete = index;
          break;
        }
        if (item.type == 1 && (!item.uDecide || item.uDecide.length <= 0)) {
          unComplete = index;
          break;
        }
      }
      this.unComplete = unComplete
      if (unComplete != -1) {
        uni.showToast({title: `第${unComplete + 1}题未作答！`})
      } else {
        uni.showModal({
          title: '提示', content: '提交后不可修改，确认提交', success: res => {
            console.log("showModal========", res)
            if (res.confirm) this.submitExamRequest()
          }
        })
      }
    },
    submitExamRequest() {
      this.question_list.forEach(que => {
        if (que.type === 0 && !que.uAnswer) que.uAnswer = []
        if (que.type === 1 && !que.uDecide) que.uDecide = ''
      })
      let endTime = new Date().getTime()
      let answerTime = endTime - this.startTime;
      // console.log("开始时间",convertDateTime(this.startTime))
      // console.log("结束时间",convertDateTime(endTime,true))
      let useTime = getMinuteValue(answerTime)
      let params = {useTime, paperId: this.paperInfo._id, question_list: this.question_list}
      this.$request('exam/exam/createExam', params).then(res => {
        uni.showToast({title: "提交成功！"})
        if (this.timer) clearInterval(this.timer)
        setTimeout(() => {
          uni.switchTab({url: rank})
        }, 1000)
      }).catch(err => {
        // debugger
        uni.showToast({title: err.message || "请求失败!"})
      })
    }
  }
}
</script>

<style>
.container {
  padding: 15px;
}

.exam-title {
  font-weight: bold;
  font-size: large;
  width: 100%;
  text-align: center;
}

.exam-time {
  font-size: small;
  margin-top: 10px;
  margin-left: 10px;
  margin-right: 10px;
  width: calc(100% - 20px);
}

.question-item {
  font-size: small;
  margin: 10px 3px;
  padding: 7px;
  border-radius: 5px;
  background: #C8C7CC;
}

.question-title {
  font-size: medium;
  font-weight: 500;
}

.question-score {
  margin-left: 5px;
  font-size: small;
  color: #007AFF;
}

.submit-view {
  color: white;
  position: fixed;
  width: 50px;
  height: 50px;
  right: 15px;
  bottom: 50px;
  background: #55aa00;
  border-radius: 50%;
  text-align: center;
}
</style>
